package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserFeign userFeign;
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //1.检查参数
        if (dto.getSize()==null||dto.getSize()<1) {
            dto.setSize(10);
        }
        if (dto.getMinDate()==null) {
            dto.setMinDate(new Date());
        }
        //2.获取评论的回复
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate())).with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(dto.getSize()), ApCommentRepay.class);
        //3.没有登陆直接返回查到的回复
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            return ResponseResult.okResult(apCommentRepays);
        }
        //4.获取回复的id
        List<String> repaysId = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        //5.获取用户的回复点赞的id
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").in(repaysId)), ApCommentRepayLike.class);
        List<String> repaysLikesId = apCommentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());
        //6.遍历所有的回复比较回复的id和点赞的id是否一致，一致那么可以把vo中的operation设置为0
        ArrayList<ApCommentRepayVo> apCommentRepayVos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(apCommentRepays)&&CollectionUtils.isNotEmpty(apCommentRepayLikes)) {
            apCommentRepays.forEach(
                    apCommentRepay -> {
                        ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                        BeanUtils.copyProperties(apCommentRepay,apCommentRepayVo);
                        if (repaysLikesId.contains(apCommentRepay.getId())) {
                            apCommentRepayVo.setOperation((short) 0);
                        }
                        apCommentRepayVos.add(apCommentRepayVo);
                    }
            );
            return ResponseResult.okResult(apCommentRepayVos);
        }
        return ResponseResult.okResult(apCommentRepays);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //1.检查参数
        //2.判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ResponseResult<ApUser> result = userFeign.findUserById(user.getId());
        ApUser apUser = result.getData();
        if (result.getCode() !=0||apUser==null) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"远程调用userFeign.findUserById失败");
        }
        //3.保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);
        //4.更新评论回复数量+1
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        apComment.setUpdatedTime(new Date());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //1.检查参数
        //2.判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.点赞操作
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if(apCommentRepay == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        // 查询是否点过赞
        if (dto.getOperation()==0) {
            if (commentRepayLike!=null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"请勿重复点赞");
            }
            //更新评论的点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
            //保存 APP评论信息点赞
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short)0);
            mongoTemplate.save(apCommentRepayLike);
        }else {
            //4.取消点赞
            apCommentRepay.setLikes(apCommentRepay.getLikes() < 0 ? 0 : apCommentRepay.getLikes() - 1);
            //更新评论的点赞数量
            mongoTemplate.save(apCommentRepay);
            //更新 APP评论信息点赞
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }
        //5.数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
